<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="题目内容" prop="title">
              <el-input v-model="queryParams.title" placeholder="请输入题目内容" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <!-- 题目类型	 -->
            <el-form-item label="题目类型" prop="type">
                <el-select clearable v-model="queryParams.type" placeholder="请选择题型" class="w-full" @keyup.enter="handleQuery">
                  <el-option label="单选题" value="0" />
                  <el-option label="多选题" value="1" />
                  <el-option label="判断题" value="2" />
                  <el-option label="主观题" value="3" />
                </el-select>
              </el-form-item>
              <el-form-item label="课程分类" prop="categoryId">
              <el-select v-model="queryParams.categoryId" clearable placeholder="请选择课程分类" @change="typeHandleCourse($event)" class="w-full">
                <el-option
                  v-for="item in courseType"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="关联课程" prop="courseId">
              <el-select clearable v-model="queryParams.courseId" placeholder="请选择关联课程" class="w-full">
                <el-option
                  v-for="item in courseOptions"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="分值" prop="score">
              <el-input v-model="queryParams.score" placeholder="请输入分值" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['bykt:simulation:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['bykt:simulation:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['bykt:simulation:remove']">删除</el-button>
          </el-col>
          <el-button type="success" @click="visibleHidden = true">文件导入</el-button>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['bykt:simulation:export']">导出模版</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="simulationList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="题目内容" align="center" prop="title" />
        <el-table-column label="题目类型" align="center" prop="type" >
            <template #default="scope">
              <span>{{ scope.row.type == 0 ? '单选题' : scope.row.type == 1 ?'多选题' : scope.row.type == 2 ?'判断题':"主观题"}}</span>
            </template>
          </el-table-column>
        <el-table-column label="选项内容" align="center" prop="options" />
        <el-table-column label="正确答案" align="center" prop="answer" />
        <el-table-column label="解析" align="center" prop="analysis" />
        <!-- <el-table-column label="图片" align="center" prop="imageUrl" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.imageUrl" :width="50" :height="50"/>
          </template>
        </el-table-column> -->
        <el-table-column label="分值" align="center" prop="score" />
        <el-table-column label="题库类型" align="center" prop="questionType">
            <template #default="scope">
              <span>考试</span>
            </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['bykt:simulation:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['bykt:simulation:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改模拟卷对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="80%" append-to-body>
      <div v-if="!batchMode">
        <el-form ref="simulationFormRef" :model="form" :rules="rules" label-width="90px">
          <el-row :gutter="20">
            <!-- 左侧列 -->
            <el-col :span="8">
              <el-form-item label="题目类型" prop="type">
                <el-select clearable v-model="form.type" placeholder="请选择题型" class="w-full" @change="handleTypeChange">
                  <el-option label="单选题" value="0" />
                  <el-option label="多选题" value="1" />
                  <el-option label="判断题" value="2" />
                  <el-option label="主观题" value="3" />
                </el-select>
              </el-form-item>


              <el-form-item label="题目内容" prop="title">
                <el-input
                  v-model="form.title"
                  type="textarea"
                  placeholder="请输入题目内容"
                  :autosize="{ minRows: 3, maxRows: 5 }"
                />
              </el-form-item>


              <el-form-item label="正确答案" prop="answer">
                <el-input v-model="form.answer" placeholder="请输入正确答案" />
              </el-form-item>

            </el-col>
            <!-- 中间 -->
            <el-col :span="8">
              <el-form-item label="分值" prop="score">
                <el-input v-model="form.score" placeholder="请输入分值" />
              </el-form-item>

              <el-form-item label="排序">
                  <el-input-number v-model="form.sort" :min="1" />
                </el-form-item>

              <el-form-item label="图片" prop="image">
                <!-- <image-upload v-model="form.image" /> -->
                <el-upload
                :headers="uploadHeaders"
                drag
                action="/dev-api/ossUpload/uploadImage"
                :on-progress="handleImageProgress"
                :on-success="handleImageSuccess"
                :before-upload="beforeImageUpload"
                :on-remove="handleImageRemove"
                :file-list="imageFileList"
                accept=".jpg,.png"
                list-type="picture-card"
              >
                <el-icon class="avatar-uploader-icon"><Plus /></el-icon>

                <template #file="{ file }">
                  <div>
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-delete"
                        @click="handleImageRemove(file)"
                      >
                        <el-icon><Delete /></el-icon>
                      </span>
                    </span>
                  </div>
                </template>
              </el-upload>
              </el-form-item>



            </el-col>
            <!-- 右侧列 -->
            <el-col :span="8">
              <!-- <el-form-item label="题库类型" prop="questionType">

                  <el-select v-model="form.questionType" placeholder="请选择题库类型" class="w-full">
                      <el-option label="习题" value="1" />
                      <el-option label="刷题" value="2" />
                      <el-option label="考试" value="3" />
                </el-select>
              </el-form-item> -->

              <el-form-item label="解析" prop="analysis">
                <el-input
                  v-model="form.analysis"
                  type="textarea"
                  placeholder="请输入解析内容"
                  :autosize="{ minRows: 3, maxRows: 5 }"
                />
              </el-form-item>
                <el-form-item label="选项内容" prop="options">
                <template v-if="form.type === '0' || form.type === '1'">
                  <div v-for="(option, index) in optionsList" :key="index" class="mb-2 flex items-center">
                    <el-input v-model="option.key" placeholder="请输入选项内容" class="mr-2" />
                    <el-input v-model="option.value" placeholder="请输入选项标识" class="mr-2 w-[80px]" />
                    <el-button type="danger" @click="removeOption(index)" :disabled="optionsList.length === 1">
                      删除
                    </el-button>
                  </div>
                  <el-button type="primary" @click="addOption" :disabled="optionsList.length >= 8">
                    新增选项
                  </el-button>
                </template>
                <el-input
                  v-else
                  v-model="form.options"
                  type="textarea"
                  placeholder="请输入选项内容（多个选项用|分隔）"
                  :autosize="{ minRows: 3, maxRows: 5 }"
                />
              </el-form-item>


            </el-col>
          </el-row>
        </el-form>

        <div class="flex justify-between mb-4">
          <!-- <el-button type="primary" @click="toggleBatchMode" v-if="dialog.title === '添加模拟卷'">
            批量添加模式
          </el-button> -->
          <div></div> <!-- 占位元素 -->
        </div>
      </div>

      <!-- 批量添加模式 -->
      <div v-else>
        <el-alert title="批量添加模式" type="info" show-icon class="mb-4" :closable="false">
          支持同时添加多道题目，每道题目单独提交
        </el-alert>

        <div v-for="(item, index) in batchQuestions" :key="index" class="batch-item mb-6 p-4 border rounded bg-gray-50">
          <div class="flex justify-between items-center mb-3">
            <span class="font-medium text-blue-600">题目 {{ index + 1 }}</span>
            <el-button type="danger" icon="Delete" circle @click="removeBatchQuestion(index)" />
          </div>

          <el-form :model="item" :rules="rules" label-width="90px">
            <el-row :gutter="15">
              <!-- 左侧 -->
              <el-col :span="8">
                <el-form-item label="题目类型" prop="type">
                <el-select v-model="form.type" clearable placeholder="请选择题型" class="w-full">
                  <el-option label="单选题" value="0" />
                  <el-option label="多选题" value="1" />
                  <el-option label="判断题" value="2" />
                  <el-option label="主观题" value="3" />
                </el-select>
              </el-form-item>

                <el-form-item label="题目内容" prop="title">
                  <el-input
                    v-model="item.title"
                    type="textarea"
                    placeholder="请输入题目内容"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                  />
                </el-form-item>

                <el-form-item label="正确答案" prop="answer">
                  <el-input v-model="item.answer" placeholder="请输入正确答案" />
                </el-form-item>

              </el-col>
              <!-- 中间 -->
              <el-col :span="8">
                  <el-form-item label="分值" prop="score">
                    <el-input v-model="item.score" placeholder="请输入分值" />
                  </el-form-item>

                  <el-form-item label="选项内容" prop="options">
                  <el-input
                    v-model="item.options"
                    type="textarea"
                    placeholder="请输入选项内容"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                  />
                </el-form-item>

                <el-form-item label="图片" prop="image">
                    <image-upload v-model="form.image" />
                </el-form-item>
              </el-col>
              <!-- 右侧 -->
              <el-col :span="8">
                <!-- <el-form-item label="题库类型" prop="questionType">

                  <el-select v-model="form.questionType" placeholder="请选择题库类型" class="w-full">
                      <el-option label="习题" value="1" />
                      <el-option label="刷题" value="2" />
                      <el-option label="考试" value="3" />
                  </el-select>
                </el-form-item> -->

                <el-form-item label="解析" prop="analysis">
                  <el-input
                    v-model="item.analysis"
                    type="textarea"
                    placeholder="请输入解析"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                  />
                </el-form-item>

              </el-col>
            </el-row>
          </el-form>
        </div>

        <div class="flex justify-between mt-4">
          <el-button type="primary" icon="Plus" @click="addBatchQuestion">
            添加题目
          </el-button>
          <!-- <el-button @click="toggleBatchMode">返回单题模式</el-button> -->
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm(props.questionType)">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <ImportXlsxs :visible="visibleHidden" :url="url" @parentFunction="parentFunction"></ImportXlsxs>
  </div>

</template>

<script setup name="Simulation" lang="ts">
import { listSimulation, getSimulation, delSimulation, addSimulation, updateSimulation } from '@/api/bykt/simulation/index';
import { SimulationVO, SimulationQuery, SimulationForm } from '@/api/bykt/simulation/types';
import { getToken } from '@/utils/auth';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import ImportXlsxs from '@/components/importXlsxs/index.vue'
import { getCourseList ,getCategoryTypeList} from '@/api/bykt/course/index';
const simulationList = ref<SimulationVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const imageFileList = ref([]);
const visibleHidden = ref(false);
const courseType=ref([]);
const courseOptions = ref([]);
const url = ref('http://localhost/dev-api/bykt/simulation/courseSimulationImportData');

const optionsList = ref([]);

const uploadHeaders = ref({
  'Authorization': `Bearer ` + getToken(), // JWT 示例
});

const queryFormRef = ref<ElFormInstance>();
const simulationFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: SimulationForm = {
  id: undefined,
  videoId: undefined,
  courseId: undefined,
  simulationId: undefined,
  title: undefined,
  type: undefined,
  options: undefined,
  answer: undefined,
  analysis: undefined,
  image: undefined,
  score: undefined,
  sort: undefined
  // questionType: undefined
}
const data = reactive<PageData<SimulationForm, SimulationQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    videoId: undefined,
    courseId: undefined,
    simulationId: undefined,
    title: undefined,
    type: undefined,
    options: undefined,
    answer: undefined,
    analysis: undefined,
    image: undefined,
    score: undefined,
    // questionType: undefined,
    params: {
    }
  },
  rules: {
    title: [
      { required: true, message: "题目内容不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "题目类型不能为空", trigger: "change" }
    ],
    answer: [
      { required: true, message: "正确答案不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
const props = defineProps({
  simulationId: {
    type: [String, Number],
    default: null
  },
  questionType: {
    type: [String, Number],
    default: null
  },
  // 添加新的props
  defaultCategoryId: {
    type: [String, Number],
    default: null
  },
  defaultCourseId: {
    type: [String, Number],
    default: null
  }
})
const typeHandleCourse = async (categoryId) => {
  // console.log(categoryId)
  try {
    const res = await getCourseList({categoryId});
    queryParams.value.courseId = undefined;
    courseOptions.value = res.rows || [];
  } catch (error) {
    console.error("获取课程列表失败:", error);
  }
}

// 添加监听题目类型变化的函数
const handleTypeChange = (value) => {
  if (value === '0' || value === '1') { // 单选题或多选题
    optionsList.value = [
      { key: '', value: '' }
    ];
  } else {
    optionsList.value = [];
  }
};
// 添加选项的函数
const addOption = () => {
  const letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
  const nextIndex = optionsList.value.length;
  if (nextIndex < letters.length) {
    optionsList.value.push({ key: '', value: "" });
  }
};

// 删除选项的函数
const removeOption = (index) => {
  optionsList.value.splice(index, 1);
};

// 转换选项为指定格式的函数
const formatOptions = () => {
  const formattedOptions = optionsList.value.map(item => ({
    id: item.value,
    text: item.key
  }));
  form.value.options = JSON.stringify(formattedOptions);
};
const parentFunction = (data) => {
  visibleHidden.value = false
  getList()
}
/** 查询模拟卷列表 */
const getList = async () => {
  console.log('来了来了',queryParams.value)
  loading.value = true;
  const res = await listSimulation({...queryParams.value,simulationId:props.simulationId,questionType:props.questionType});
  // const res = await listSimulation({...queryParams.value,simulationId:props.simulationId,questionType:props.questionType,courseId:props.defaultCourseId,categoryId:props.defaultCategoryId});
  simulationList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  batchMode.value = false;
  dialog.visible = false;
  imageFileList.value = []
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData,
    questionType: props.questionType
  };
  simulationFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  console.log(queryParams.value)
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
  fetchCourseList()
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: SimulationVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  batchMode.value = false; // 确保初始为单题模式
  dialog.visible = true;
  dialog.title = "添加模拟卷"
  imageFileList.value = [];
}

/** 修改按钮操作 */
const handleUpdate = async (row) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getSimulation(_id);
  Object.assign(form.value, res.data);

  // 如果是单选题或多选题，解析选项内容
  if (form.value.type === '0' || form.value.type === '1') {
    try {
      const options = JSON.parse(form.value.options || '[]');
      optionsList.value = options.map(item => ({
        key: item.text,
        value: item.id
      }));
    } catch (error) {
      optionsList.value = [{ key: '', value: '' }];
      console.error('解析选项失败:', error);
    }
  }

  // 处理图片
  if (form.value.image) {
    imageFileList.value = [{
      name: '已上传图片',
      url: form.value.image
    }];
  } else {
    imageFileList.value = [];
  }

  dialog.visible = true;
  dialog.title = "修改题目";
};

/** 删除按钮操作 */
const handleDelete = async (row?: SimulationVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('确认是否删除数据？').finally(() => loading.value = false);
  await delSimulation(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('bykt/simulation/export', {
    ...queryParams.value
  }, `模拟卷模版_${new Date().getTime()}.xlsx`)
}

const batchMode = ref(false);
const batchQuestions = ref<SimulationForm[]>([{ ...initFormData }]);

// 切换批量模式
const toggleBatchMode = () => {
  batchMode.value = !batchMode.value;
  if (batchMode.value) {
    // 进入批量模式时初始化一道题目
    batchQuestions.value = [{ ...initFormData }];
  } else {
    // 退出批量模式时清空批量数据
    batchQuestions.value = [];
  }
};

// 添加批量题目
const addBatchQuestion = () => {
  batchQuestions.value.push({ ...initFormData });
};

// 删除批量题目
const removeBatchQuestion = (index: number) => {
  if (batchQuestions.value.length > 1) {
    batchQuestions.value.splice(index, 1);
  } else {
    proxy?.$modal.msgWarning("至少保留一道题目");
  }
};

// 修改提交表单方法
const submitForm = async (questionType) => {
  if (batchMode.value) {
    // 批量提交模式
    buttonLoading.value = true;
    console.log("批量提交数据:", batchQuestions.value);
    try {
      const promises = batchQuestions.value.map(question => {
        return addSimulation(question);
      });

      await Promise.all(promises);
      proxy?.$modal.msgSuccess(`成功添加 ${batchQuestions.value.length} 道题目`);
      dialog.visible = false;
      await getList();
      imageFileList.value = []
    } catch (e) {
      console.error("批量添加失败:", e);
    } finally {
      buttonLoading.value = false;
    }
  } else {
    // 原有单题提交逻辑
    simulationFormRef.value?.validate(async (valid) => {
      if (valid) {
        buttonLoading.value = true;
        console.log(valid)
        try {
          // 如果是单选题或多选题，先格式化选项
          if (form.value.type === '0' || form.value.type === '1') {
            formatOptions();
          }
          if (form.value.id) {

            await updateSimulation(form.value);
          } else {
            await addSimulation({...form.value, questionType,simulationId:props.simulationId,courseId:props.defaultCourseId});
          }
          proxy?.$modal.msgSuccess("操作成功");
          dialog.visible = false;
          await getList();
          imageFileList.value = [];
        } catch (e) {
          console.error("操作失败:", e);
        } finally {
          buttonLoading.value = false;
        }
      }
    });
  }
};
const handleImageProgress = (event) => {
  // imageProgress.value = event.percent;
}
const handleImageSuccess = (response, file) => {
  imageFileList.value = [];
  // 添加延迟，确保DOM更新
  setTimeout(() => {
    imageFileList.value = [{
      name: file.name,
      url: response.data
    }];
    form.value.image = response.data;
  }, 10);
}

const handleImageRemove = () => {
  // 清空图片字段
  form.value.image = "";
  imageFileList.value = [];
}
const beforeImageUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG格式的图片!');
    return false;
  }
  if (form.value.image) {
    // 清空现有文件列表，以便上传新文件
    // imageFileList.value = [];
    // handleImageRemove()
  }
  return true;
}

const fetchCourseList = async (categoryId) => {
  try {
    const res = await getCourseList({categoryId});
    courseOptions.value = res.rows || [];
  } catch (error) {
    console.error("获取课程列表失败:", error);
  }
};
const fetchCourseTypeList = async () => {
  try {
    const res = await getCategoryTypeList({});
    courseType.value = res.rows || [];
    if (props.defaultCategoryId) {
    queryParams.value.categoryId = props.defaultCategoryId
  }
  if (props.defaultCourseId) {
    queryParams.value.courseId = props.defaultCourseId
  }
  } catch (error) {
    console.error("获取课程分类列表失败:", error);
  }
};
onMounted(() => {
  queryParams.value.categoryId = props.defaultCategoryId
  queryParams.value.courseId = props.defaultCourseId
  getList();
  fetchCourseList(props.defaultCategoryId || undefined)
  fetchCourseTypeList()
  // handleQuery()

});

</script>

<style scoped>
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 64px;
  text-align: center;
}
.batch-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fafafa;
  transition: all 0.3s;
}

.batch-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
